package com.speedy.course.ext

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.ConcatAdapter
import androidx.recyclerview.widget.RecyclerView
import com.speedy.course.databinding.ItemEmptyStateBinding

fun RecyclerView.Adapter<*>.withEmptyBody(): ConcatAdapter {
    return withEmptyBody { parent ->
        ItemEmptyStateBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        ).root
    }
}

fun RecyclerView.Adapter<*>.withEmptyBody(viewProvider: (parent: ViewGroup) -> View): ConcatAdapter {
    val emptyStateAdapter = EmptyStateAdapter(viewProvider)
    emptyStateAdapter.isEmpty = itemCount == 0
    registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() {

        override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
            emptyStateAdapter.isEmpty = this@withEmptyBody.itemCount == 0
        }

        override fun onItemRangeRemoved(positionStart: Int, itemCount: Int) {
            emptyStateAdapter.isEmpty = this@withEmptyBody.itemCount == 0
        }

        override fun onChanged() {
            emptyStateAdapter.isEmpty = this@withEmptyBody.itemCount == 0
        }
    })
    return ConcatAdapter(emptyStateAdapter, this)
}


class EmptyStateAdapter(private val viewProvider: (parent: ViewGroup) -> View) :
    RecyclerView.Adapter<EmptyStateViewHolder>() {

    var isEmpty: Boolean = false
        set(value) {
            //LogProcessor.d("EmptyBody", "setEmpty field = $field value = $value")
            if (field && !value) {
                notifyItemRemoved(0)
            } else if (value && !field) {
                notifyItemInserted(0)
            }
            field = value
        }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): EmptyStateViewHolder {
        return EmptyStateViewHolder(
            viewProvider.invoke(parent)
        )
    }

    override fun onBindViewHolder(holder: EmptyStateViewHolder, position: Int) {
    }

    override fun getItemCount(): Int {
        return if (isEmpty) 1 else 0
    }
}

class EmptyStateViewHolder(view: View) : RecyclerView.ViewHolder(view)